import {
	createRouter,
	createWebHashHistory,
	createWebHistory
} from 'vue-router'
import store from '../store'

import defaultRoutes from "./defaultRoutes";
import components from "./components";

var router = createRouter({
	history: createWebHistory('/hgzx/'),
	routes: defaultRoutes
})

/**
 * 添加路由
 * @param {Object} item 菜单项
 */
function addRoute(item) {
	console.debug("addRoute", item.url)
	var componentPath = item.code;
	var routeObj = {
		name: item.code,
		path: item.url,
		// component: () => import(componentPath),
		component: components[componentPath],
		meta: {
			title: item.name,
			icon: item.icon,
			messageNum: null,
			hidden: item.hidden,
			keepAlive: item.keepAlive
		}
	}

	router.addRoute('Layout', routeObj)

	if (item.children) {
		item.children.forEach(function(item, index) {
			addRoute(item);
		})
	}
}

var NotFound = {
	path: "/:pathMatch(.*)*",
	name: 'NotFound',
	redirect: '/404'
}

/**
 * 初始化动态路由
 * @param {Object} menuTree
 */
router.initRoutes = async function(menuTree) {
	if (router.hasRoute("NotFound")) {
		router.removeRoute("NotFound");
	}

	await store.commit("auth/setMenuTree", menuTree);
	await menuTree.forEach(function(item, index) {
		addRoute(item);
	})

	//最后再添加404跳转路由
	router.addRoute(NotFound);
}

router.beforeEach((to, from, next) => {
	//设置页面title
	if (to.meta.title) {
		document.title = '回归自性 | ' + to.meta.title;
	}

	//记录上一页, 返回组件使用
	store.commit('goback/prePage', from);
	console.log('$route from', store.state.goback.prePage);

	next();
})

export default router
